package com.zx.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.ruiji.common.CustomException;
import com.zx.ruiji.common.R;
import com.zx.ruiji.dto.DishDto;
import com.zx.ruiji.entity.Category;
import com.zx.ruiji.entity.Dish;
import com.zx.ruiji.entity.DishFlavor;
import com.zx.ruiji.service.CategoryService;
import com.zx.ruiji.service.DishFlavorService;
import com.zx.ruiji.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * 需要同时操作两张表，即添加菜品和口味数据，所以需要重写save方法，不能直接调用save
     * dishService.save(dishDto);
     * 此时需要自定义saveWithFlavor()来操作
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //优化：清理保存的菜品缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增成功");
    }

    //菜品信息的分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
//        分页构造器
        Page<Dish> pageInfo = new Page(page, pageSize);
        Page<DishDto> dishDtoPage = new Page(page, pageSize);
//        条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        分页页面展示形式
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
//        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
//        分页查询
        dishService.page(pageInfo, queryWrapper);

//        展示菜品分类名称
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    //根据id查询菜品信息和对应的口味信息--修改回显
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改菜品，点击保存时触发
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //优化：清理修改菜品缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }


    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam  List<Long> ids){
        log.info("删除的属性为：{}",ids);

        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        wrapper.eq("status",1);
        int count = dishService.count(wrapper);
        if (count>0){
            throw  new CustomException("当前菜品在售无法删除");
        }

        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 批量起售
     * id = 将要修改的状态
     * @return
     */
    @PostMapping("/status/{id}")
    public R StartingAt(@PathVariable Integer id,@RequestParam List<Long> ids){
        log.info("status：{}，ids：{}",id,ids);

        List<Dish> list = dishService.listByIds(ids);
        List<Dish> dishList = list.stream().map(item -> {
            item.setStatus(id);
            dishService.updateById(item);
            return item;
        }).collect(Collectors.toList());


        return R.success(dishList);
    }

    //删除菜品
//    @DeleteMapping
//    public R<String> delete(@RequestParam List<Long> ids) {
//        log.info("删除菜品ids:{}", ids);
//        int count = 0;
//        for (Long id : ids) {
//            DishDto dishDto = dishService.getByIdWithFlavor(id);
//            log.info("删除菜品dishDto:{}", dishDto);
//            Integer status = dishDto.getStatus();
//            log.info("删除菜品status:{}", status);
//            if (status == 0) {
//                dishService.removeById(id);
//                count++;
//            }
//        }
//        if (count == ids.size()) {
//            return R.success("停售商品删除成功");
//        }
//        return R.error("起售商品不能删除");
//    }
//
//
//    //状态修改，批量操作前端出bug
//    @PostMapping("/status/{status}")
//    public R changeStatus(@PathVariable int status, String ids) {
//        String[] idList = ids.split(",");
//        log.info("改变菜品转态ids:{}", ids);
//        for (String id : idList) {
//            Dish dish = new Dish();
//            dish.setId(Long.parseLong(id));
//            dish.setStatus(status);
//            dishService.updateById(dish);
//        }
//
//        return R.success("更新状态成功");
//    }

    //小程序页面菜品展示
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        List<DishDto> dishDtoList = null;

        //优化：动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //优化：先从Redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //优化：如果存在，直接返回，无需查询数据库
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());


        //优化：如果不存在，查询数据库，将查询到的数据缓存到Redis中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }


}
